package com.yjs.app.trade.web.controller.business;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.miemiedev.mybatis.paginator.domain.Order;
import com.yjs.app.trade.core.util.PropertiesUtils;
import com.yjs.app.trade.core.util.StringUtils;
import com.yjs.app.trade.entity.base.BusinessConstant;
import com.yjs.app.trade.entity.base.util.Page;
import com.yjs.app.trade.entity.bean.CompanySearch;
import com.yjs.app.trade.entity.bean.MemberSearch;
import com.yjs.app.trade.service.service.business.member.MemberService;
import com.yjs.app.trade.service.service.business.search.NewSearchListService;
import com.yjs.app.trade.service.service.sys.UserService;
import com.yjs.app.trade.service.service.util.search.SearchConditionUtil;
import com.yjs.app.trade.web.controller.base.BaseController;
import com.yjs.app.trade.web.controller.base.util.Result;
import com.yjs.list.model.ListParamBase;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/app/business/member")
public class MemberController extends BaseController {

	@Autowired
	MemberService memberService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	NewSearchListService newSearchListService;

	public static String yjsbdJdbcName=PropertiesUtils.getProperty("jdbc.databasename.yjsbd");
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/findDispatchCompany", method = RequestMethod.GET)
	@ResponseBody
	public Object findDispatchCompany(Page<CompanySearch> page, CompanySearch companySearch, String data) {
		JSONObject jsonObject = dpackData(data);
		if (jsonObject.get("list") != null) {
			List<String> list = jsonObject.getJSONArray("list");
			for (String string : list) {
				companySearch.getList().add(string);
			}
		}
		if (jsonObject.get("companyName") != null) {
			companySearch.setCompanyName(jsonObject.getString("companyName"));
		}
		page.setPageNo(jsonObject.getInt("pageNo"));
		if (jsonObject.get("pageSize") != null) {
			page.setPageSize(jsonObject.getInt("pageSize"));
		}
		return Result.csuccess(memberService.findDispatchCompany(page, companySearch));
	}

	@RequestMapping(value = "/findSellerCompany", method = RequestMethod.GET)
	@ResponseBody
	public Object findSellerCompany(Page<CompanySearch> page, CompanySearch companySearch, String data, HttpServletRequest request) {
		JSONObject jsonObject = dpackData(data);
		page.setPageNo(jsonObject.getInt("pageNo"));
		if (jsonObject.get("pageSize") != null) {
			page.setPageSize(jsonObject.getInt("pageSize"));
		}
		if (jsonObject.get("companyName") != null) {
			companySearch.setCompanyName(jsonObject.getString("companyName"));
		}
		return Result.csuccess(memberService.findSellerCompany(page, companySearch));
	}

	@RequestMapping(value = "/findPlatFormGeoList", method = RequestMethod.GET)
	@ResponseBody
	public Object findPlatFormGeoList() {
		return Result.csuccess(memberService.findPlatFormGeoList());
	}
	@RequestMapping(value = "/findCQRegion")
	@ResponseBody
	public Object findCQRegio(HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		return Result.csuccess(memberService.getRegionListSort("500000"));
	}
	
	@RequestMapping(value = "/getRegionList", method = RequestMethod.GET)
	@ResponseBody
	public Object getRegionList(String data) {
		JSONObject jsonObject = dpackData(data);
		if (jsonObject.get("parentId") != null) {
			return Result.csuccess(memberService.getRegionList(jsonObject.get("parentId").toString()));
		} else {
			return Result.csuccess(memberService.getRegionList("COUNTRY_CN"));
		}
	}
	
	@RequestMapping(value = "/findDispatchBySeller", method = RequestMethod.GET)
	@ResponseBody
	public Object findDispatchBySeller(String data, HttpServletRequest request) {
		return Result.csuccess(memberService.findDispatchBySeller(getUserMemberId(request)));
	}
	
	@RequestMapping(value = "/findMembersByUnionMemberId", method = RequestMethod.GET)
	@ResponseBody
	public Object findMembersByUnionMemberId(String data, HttpServletRequest request, Page<MemberSearch> page, MemberSearch memberSearch) {
		memberSearch.setUnionId(getUserMemberId(request));
		if (StringUtils.isNotBlank(data)) {
			JSONObject jsonObject = dpackData(data);
			if (StringUtils.strIsNotNull(jsonObject.get("memberName"))) {
				memberSearch.setMemberName(jsonObject.getString("memberName"));
			}
			if (StringUtils.strIsNotNull(jsonObject.get("pageSize"))) {
				page.setPageSize(jsonObject.getInt("pageSize"));
			}
			if (StringUtils.strIsNotNull(jsonObject.get("pageNo"))) {
				page.setPageNo(jsonObject.getInt("pageNo"));
			}
		}
		return Result.csuccess(memberService.findMembersByUnionMemberId(page, memberSearch));
	}
	
	@RequestMapping(value = "/findUnionMemberById", method = RequestMethod.GET)
	@ResponseBody
	public Object findUnionMemberById(String data, HttpServletRequest request, MemberSearch memberSearch) {
		if (StringUtils.isNotBlank(data)) {
			JSONObject jsonObject = dpackData(data);
			if (StringUtils.strIsNotNull(jsonObject.get("memberId"))) {
				memberSearch.setMemberId(jsonObject.getString("memberId"));
			}
		}
		return Result.csuccess(memberService.findUnionMemberById(memberSearch));
	}
	
	@RequestMapping(value = "/getTradeStatusNumber", method = RequestMethod.GET)
	@ResponseBody
	public Object getTradeStatusNumber(HttpServletRequest request, String data) {
		JSONObject jsonObject = dpackData(data);
		String type = jsonObject.getString("type");
		String status [] = jsonObject.getString("status").split(",");
		String memberId = getUserMemberId(request);
		int memberType = getUserMemberType(request);
		int pageNo = 1;
		int pageSize = 1;
		List<ListParamBase> listParamBases = new ArrayList<ListParamBase>();
		List<Order> orders = new ArrayList<>();
		Map<String, Integer> map = new HashMap<String, Integer>();
		String memberIds = "";
		boolean flag = true;
		List<Map<String, Object>> passportsMap = userService.getPassportSalesAut(getUserId(request));
		if (StringUtils.strIsNull(passportsMap.get(0).get("adminPassportId"))) {
			flag = false;
			for (Map<String, Object> usermap : passportsMap) {
				if (usermap.get("memberId") != null) {
					if (StringUtils.isBlank(memberIds)) {
						memberIds += usermap.get("memberId").toString();
					} else {
						memberIds +=  "," + usermap.get("memberId").toString();
					}
				}
			}
		}
		
		for (String string : status) {
			listParamBases = new ArrayList<ListParamBase>();
			orders = new ArrayList<>();
			ListParamBase paramBase = new ListParamBase();
			paramBase.setFieldName(getStatusCode(type));// 搜索字段名
			if (string.indexOf("|") != -1) {
				paramBase.setValue1(string.replace("|", ","));// 搜索值
				paramBase.setFieldTypeId("String");
				paramBase.setEnumSearchType("or");
				listParamBases.add(paramBase);
			} else {
				paramBase.setValue1(string);// 搜索值
				paramBase.setFieldTypeId("String");
				paramBase.setEnumSearchType("eq");
				listParamBases.add(paramBase);
			}
			if (!flag) {
				if (StringUtils.strIsNotNull(memberIds)) {
					listParamBases.add(SearchConditionUtil.getParamBaseValue("BUYER_ID", memberIds,"String", "or"));
				} else {
					map.put(string,0);
					continue;
				}
			}
			map.put(string, Integer.parseInt(newSearchListService.listSearchIndexs(SearchConditionUtil.searchMap(
				type, memberId, memberType, listParamBases, pageNo, pageSize, orders)).get("page").toString()));
		}
		return Result.csuccess(map);
	}
	
	private String getStatusCode (String code) {
		if (StringUtils.equals(BusinessConstant.Number.APPARCONTRACT, code) || 
				StringUtils.equals(BusinessConstant.Number.DRAGCONTRACT, code)) {
			return "STATUS_CODE";
		} else if (StringUtils.equals(BusinessConstant.Number.DRAGORDER, code) || 
				StringUtils.equals(BusinessConstant.Number.APPARORDER, code)) {
			return "DETAIL_STATE_CODE";
		} else {
			return "DETAIL_STATE_CODE";
		}
	}
	
	@RequestMapping(value = "/findMemberAppVSAppPackage", method = RequestMethod.GET)
	@ResponseBody
	public Object findMemberAppVSAppPackage(HttpServletRequest request) {
		return Result.csuccess(memberService.findMemberAppVSAppPackage(getUserMemberId(request)));
	}
	
	@RequestMapping(value = "/findMemberAppVSIsExpire", method = RequestMethod.GET)
	@ResponseBody
	public Object findMemberAppVSIsExpire(HttpServletRequest request) {
		return Result.csuccess(memberService.findMemberAppVSIsExpire(getUserMemberId(request)));
	}
	
	/**
	 * 查询诚信评价
	 * @author zjh
	 * @param request
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/findIntegrity", method = RequestMethod.GET)
	@ResponseBody
	public Object findIntegrity(HttpServletRequest request, String data) {
		JSONObject jsonObject = dpackData(data);
		String regionId = jsonObject.getString("regionId");
		String userMemberId = getUserMemberId(request);
		//String userMemberId = "user107396";
		String year = jsonObject.getString("year");
		Map<String,Object> map=new HashMap<>();
		map.put("memberId", userMemberId);
		map.put("regionId", regionId);
		map.put("jdbcName", yjsbdJdbcName);
		map.put("year", year);
		List<Map<String,Object>> list=memberService.findIntegrity(map);
		for (Map<String, Object> result : list) {
			result=changeNumber(result);
		}
		return Result.csuccess(list);	
	}

	/**
	 * 查询诚信评价详情
	 * @author zjh
	 * @param request
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/findIntegrityInformation", method = RequestMethod.GET)
	@ResponseBody
	public Object findIntegrityInformation(HttpServletRequest request, String data) {
		JSONObject jsonObject = dpackData(data);
		if(jsonObject.get("wdCode") ==null){
			String regionId = "500000";
			String userMemberId = getUserMemberId(request);
			SimpleDateFormat sd=new SimpleDateFormat("yyyy-4-MM");
			Calendar cal=Calendar.getInstance();
			cal.setTime(new Date());
			cal.add(Calendar.MONTH, -1);
			String wdCode = sd.format(cal.getTime());
			Map<String, Object> result = findIntegrity(regionId, userMemberId, wdCode);
			if (result != null && result.size() > 0){
			result = changeNumber(result);
			return Result.csuccess(result);
			}
			return Result.csuccess(result);	
		}
		String regionId = jsonObject.getString("regionId");
		String userMemberId = getUserMemberId(request);
		String wdCode = jsonObject.getString("wdCode");
		Map<String, Object> result = findIntegrity(regionId, userMemberId, wdCode);
		if (result != null && result.size() > 0){
			result = changeNumber(result);
			return Result.csuccess(result);
		}
		return Result.csuccess();	
	}

	private Map<String, Object> findIntegrity(String regionId, String userMemberId, String wdCode) {
		Map<String,Object> map=new HashMap<>();
		map.put("memberId", userMemberId);
		map.put("jdbcName", yjsbdJdbcName);
		map.put("regionId", regionId);
		map.put("wdCode", wdCode);
		Map<String,Object> result=memberService.findIntegrityInformation(map);
		return result;
	}
	
	/**
	 * 首页诚信评价
	 * @author zjh
	 * @param request
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/findIntegrityTotal", method = RequestMethod.GET)
	@ResponseBody
	public Object findIntegrityTotal(HttpServletRequest request) {
		String regionId = "500000";
		String userMemberId = getUserMemberId(request);
		SimpleDateFormat sd=new SimpleDateFormat("yyyy-4-MM");
		Calendar cal=Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.MONTH, -1);
		String wdCode = sd.format(cal.getTime());
		Map<String,Object> map=new HashMap<>();
		map.put("memberId", userMemberId);
		map.put("jdbcName", yjsbdJdbcName);
		map.put("regionId", regionId);
		map.put("wdCode", wdCode);
		Map<String,Object> result=memberService.findIntegrityScope(map);
		if(result == null || result.size()<1){
			result =new HashMap<>();
			result.put("TOTAL_SCORE", 0);
		}
		Calendar cal2=Calendar.getInstance();
		cal2.setTime(new Date());
		cal2.add(Calendar.MONTH, -2);
		String wdCode2 = sd.format(cal2.getTime());
		map.put("wdCode", wdCode2);
		Map<String,Object> result2=memberService.findIntegrityScope(map);
		if(result2 == null || result2.size()<1){
			result2= new HashMap<>();
			result2.put("TOTAL_SCORE", 0);
		}
		double score=Double.parseDouble(result.get("TOTAL_SCORE").toString());
		result = changeNumber(result);
		double score2=Double.parseDouble(result2.get("TOTAL_SCORE").toString());
		if(score>score2){
			result.put("up", "1");
		}else if(score<score2){
			result.put("up", "0");
		}else{
			result.put("up", "3");
		}
		result.put("url", "resources/html/dist/index.html#/faithdetail");
		return Result.csuccess(result);	
	}
	
	public static Map<String, Object> changeNumber(Map<String, Object> result) {
		/*if (StringUtils.strIsNull(result.get("TOTAL_SCORE"))) {
			return result;
		}*/
		String total = result.get("TOTAL_SCORE").toString();
		if(total.indexOf('.') >= 1 && total.substring(total.indexOf('.')+1).length() > 2){	
			float floatValue = new BigDecimal(result.get("TOTAL_SCORE").toString()).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
			result.put("TOTAL_SCORE",floatValue);
			return result;
		}
		return result;
	}
	
	public static void main(String[] args) {
		SimpleDateFormat sd=new SimpleDateFormat("yyyy-4-MM");
		Calendar cal=Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.MONTH, -1);
		String format = sd.format(cal.getTime());
		//System.out.println(format);
		Calendar cal2=Calendar.getInstance();
		cal2.setTime(new Date());
		cal2.add(Calendar.MONTH, -2);
		String format2 = sd.format(cal2.getTime());
		//System.out.println(format2);
	}
	
}
